import sys, os
import re
import codecs
from collections import OrderedDict
import math
import numpy as np


def get_avg_gop():
    pass


def read_corr_ids(corr_id_file):
    corr_id2map = dict()
    with codecs.open(filename=corr_id_file, mode='r') as f:
        for i in f.readlines():
            corr_id2map[i.strip()] = 1

    return corr_id2map


def read_features(features_filename, threshold, corr_id_file= ""):
    id2gop = dict()
    corr_ids = read_corr_ids("corr.ids")
    gop_outname = ctm_features + "_lt" + str(threshold).zfill(0) + ".txt"
    outf = codecs.open(filename=gop_outname, mode='w')
    with codecs.open(filename=features_filename, mode='r') as f:
        line = f.readline()
        temp_gops = []
        prev_id = ""
        while line is not None and line != "":
            line_units = re.split(r"\s+", line.strip())
            line = f.readline().strip()
            if line_units[0] not in corr_ids:
                continue
            if line_units[4] == "SIL" or line_units[4] == "SPN":
                continue
            if prev_id == "":
                temp_gops.append(float(line_units[6])) if len(line_units) >= 7 else -1000
                prev_id = line_units[0]
            else:
                if line_units[0] != prev_id:
                    avg_gop = np.average(temp_gops)
                    print('{} {}, {}\n'.format(prev_id, temp_gops, avg_gop))
                    if avg_gop >= float(threshold):
                        id2gop[prev_id] = avg_gop
                        outf.write('{} {}\n'.format(prev_id,avg_gop))
                    prev_id = line_units[0]
                    temp_gops.clear()
                    temp_gops.append(float(line_units[6])) if len(line_units) >= 7 else -1000
                else:
                    temp_gops.append(float(line_units[6])) if len(line_units) >= 7 else -1000

    outf.close()
    return id2gop


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('{} {}\n'.format(sys.argv[0], "<gop threshold>"))
        sys.exit(-1)
    ctm_features, threshold = sys.argv[1], float(sys.argv[2])
    id2gop = read_features(ctm_features, threshold)

